<?php

use App\Components\EventService;

if (!function_exists('event')) {
    /**
     * 事件分发
     * @param string $event 事件名称
     * @param mixed $payload 事件消息体
     * @param array $option delay=延迟发送秒数, live=消息生存秒数
     * @return bool 是否发送成功
     */
    function event(string $event, $payload = [], array $option = []): bool
    {
        return EventService::dispatch($event, $payload, $option);
    }
}

if (!function_exists('nodeTree')) {
    /**
     * 一维数组列表 转 多维树型列表
     * @param array &$list 一维数组 源数据
     * @param array &$tree 多维数组 终数据
     * @param string $pidKey 父节点标识键名
     * @param int $pidValue 父节点起始值
     */
    function nodeTree(array &$list, array &$tree, string $pidKey = 'pid', int $pidValue = 0): void
    {
        foreach ($list as $k => $v) {
            if ($pidValue == $v[$pidKey]) {
                !isset($v['children']) && $v['children'] = [];
                $tree[$v['id']] = $v;
                unset($list[$k]);
                nodeTree($list, $tree[$v['id']]['children'], $pidKey, $v['id']);
            }
        }
    }
}

if (!function_exists('nodeTreeValue')) {
    function nodeTreeValue(array $list): array
    {
        foreach ($list as &$v) {
            if (!isset($v['children'])) {
                continue;
            }
            if (count($v['children']) == 0) {
                unset($v['children']);
                continue;
            }
            $v['children'] = nodeTreeValue($v['children']);
        }
        unset($v);
        return array_values($list);
    }
}
